package com.sqllog.admin.auth.config;

import com.sqllog.admin.auth.process.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import javax.annotation.Resource;

/**
 * 权限配置
 *
 * @author chennengcheng
 * @date 2022-01-21 17:02
 * @remark
 */

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {


    @Resource
    private SecureLogoutHandler securityLogoutHandler;

    @Resource
    private SecureAuthenticationSuccessHandler secureAuthenticationSuccessHandler;

    @Resource
    private SecureAuthenticationFailureHandler securityAccessFailureHandler;

    @Resource
    private SecureRememberMeHandler rememberMeAuthenticationSuccessHandler;

    /**
     * remember me redis持久化
     */
    @Resource
    private PersistentTokenRepository securityUserTokenService;

    /**
     * 实现userservice
     */
    @Resource
    private UserDetailsService securityUserDetailsService;

    /**
     * 退出登录处理类
     */
    @Resource
    private SecureLogoutSuccessHandler securityAccessLogoutHandler;


    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    public static void main(String[] args) {
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String admin = bCryptPasswordEncoder.encode("admin");
        System.out.println(admin);
    }

    /**
     * 认证用户的来源
     *
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //数据库中
        auth.userDetailsService(securityUserDetailsService).passwordEncoder(passwordEncoder());
    }

    /**
     * 配置SpringSecurity相关信息
     *       - /login/**  # 开放登录接口
     *       - /system/captcha/** # 开放验证码接口
     *       - /assets/** # 开放静态资源
     *       - /admin/** # 开放静态资源
     *       - /component/** # 开放静态资源
     *       - /favicon.ico # 开放FAVICON
     * @param http
     * @throws Exception
     */
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/login", "/system/**", "/login", "/login/**", "/assets/**", "/admin/**", "/component/**", "/favicon.ico").permitAll()
                // 其他的需要登录后才能访问
                .anyRequest().authenticated()
                .and()
                .httpBasic()
                .and()
                .formLogin()
                // 登录页面
                .loginPage("/login")
                // 登录接口
                .loginProcessingUrl("/login")
                // 配置登录成功自定义处理类
                .successHandler(secureAuthenticationSuccessHandler)
                // 配置登录失败自定义处理类
                .failureHandler(securityAccessFailureHandler)
                .and()
                .logout()
                .addLogoutHandler(securityLogoutHandler)
                // 退出登录删除 cookie缓存
                .deleteCookies("JSESSIONID")
                // 配置用户登出自定义处理类
                .logoutSuccessHandler(securityAccessLogoutHandler)
                .and()
                .exceptionHandling()
                .and()
                .rememberMe()
                .rememberMeParameter("remember-me")
                .rememberMeCookieName("rememberme-token")
                .authenticationSuccessHandler(rememberMeAuthenticationSuccessHandler)
                .tokenRepository(securityUserTokenService)
                .and()
                .sessionManagement()
                .sessionFixation()
                .migrateSession()
                // 在需要使用到session时才创建session
                .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED);

        // 取消跨站请求伪造防护
        http.csrf().disable();
        // 防止iframe 造成跨域
        http.headers().frameOptions().disable();
    }

}
